package logic

import (
	"context"
	"house123/B/api/pkg"
	"net/http"
	"path/filepath"
	"time"

	"house123/B/api/internal/svc"
	"house123/B/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewUpdateLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateLogic {
	return &UpdateLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateLogic) Update(req *http.Request) (resp *types.Response, err error) {
	// todo: add your logic here and delete this line
	file, m, err := req.FormFile("img")
	if err != nil {
		return nil, err
	}
	if m.Size >= 2*1024*1024 {
		return &types.Response{
			Code: 500,
			Msg:  "文件尺寸不能超过2MB",
			Data: nil,
		}, nil
	}
	Ext := filepath.Ext(m.Filename)
	if Ext != ".png" && Ext != ".jpg" {
		return &types.Response{
			Code: 500,
			Msg:  "文件格式不是 png 或 jpg",
			Data: nil,
		}, nil
	}
	firename := time.Now().Format("2006-01-02 15:04:05") + Ext
	update, err := pkg.Update(file, m, firename)
	if err != nil {
		return nil, err
	}
	return &types.Response{
		Code: 200,
		Msg:  "图片上传成功",
		Data: map[string]interface{}{
			"update": update,
		},
	}, nil
}
